import React, { PureComponent } from 'react';
import _ from 'lodash';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import { SingleDateC, PrimaryC, TableC, InputC, TradingMarketC, InputNumberC, SelectC } from '../../../comps';
import config from '../../../comps/business/tradingMarket/config';
import { connect } from 'dva';
import moment from 'moment';
import accounting from 'accounting';
import config1 from '../../../utils/tableMoreIdConfig';
import { findValueByCode, formSelectData } from '../../../utils/utils';

const {
  valuateAnalysis: { valuateAnalysisTable },
} = config1;
@Form.create()
@connect(({ globalM, valuationAnalysisM, loading, userM: user }) => ({ valuationAnalysisM, loading, user, globalM }))
export default class valuateAnalysisInfoTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      editRow: undefined,
      columns: [
        {
          title: '持仓类型',
          dataIndex: 'positionType',
          key: 'positionType',
        },
        {
          title: '资产类型',
          dataIndex: 'secType',
          key: 'secType',
        },
        {
          title: '回购类型',
          dataIndex: 'repoType',
          key: 'repoType',
        },
        {
          title: '交易属性',
          dataIndex: 'attrCode',
          key: 'attrCode',
        },
        {
          title: '证券代码',
          dataIndex: 'assetDebtCode',
          key: 'assetDebtCode',
        },
        {
          title: '证券名称',
          dataIndex: 'secuabbr',
          key: 'secuabbr',
        },
        {
          title: '交易市场',
          dataIndex: 'exchangeCode',
          key: 'exchangeCode',
        },
        {
          title: '持仓数量',
          dataIndex: 'bottomPositionNum',
          key: 'bottomPositionNum',
        },
        {
          title: '单位成本',
          dataIndex: 'unitCost',
          key: 'unitCost',
        },
        {
          title: '总成本',
          dataIndex: 'costPrice',
          key: 'costPrice',
        },
        {
          title: '折算人民币市值(元)',
          dataIndex: 'bottomAssetRMBValue',
          key: 'bottomAssetRMBValue',
        },
        {
          title: '持仓日期',
          dataIndex: 'positionDate',
          key: 'positionDate',
        },
      ],
      dataSource: [],
      dictArr: ['QT', 'QH_S', 'QH_B', 'XJ'], // 资产类型不展示的字典
    };
  }

  componentDidMount() {}

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.dataSource) !== JSON.stringify(this.props.dataSource)) {
      this.setState({
        dataSource: nextProps.dataSource,
        editRow: undefined,
      });
      this.props.onChange(nextProps.dataSource);
    }
  }

  add = () => {
    const { dataSource, editRow } = this.state;
    if (editRow) return;
    const row = {
      id: Math.round(Math.random() * 10000000),
      editType: 'add', // 记录是新增还是编辑
    };
    this.setState({
      editRow: row,
      positionType: undefined,
      dataSource: [
        {
          ...row,
          isEdit: true,
        },
        ...dataSource,
      ],
    });
  };

  // 保存
  saveItem = (e) => {
    const { dataSource, editRow } = this.state;
    const { form } = this.props;
    const { validateFields } = form;
    validateFields((err, values) => {
      if (err) return;
      // 现在校验唯一性的应该是code+exchangecode+positiondate+交易属性+持仓类型
      const t = dataSource.find((x) => {
        let flag;
        // 有交易属性
        if (
          x.attrCode == values.attrCode &&
          x.positionDate == values.positionDate?.format('YYYY-MM-DD') &&
          x.assetDebtCode !== '--' &&
          x.assetDebtCode == values.assetDebtCode &&
          x.positionType == values.positionType &&
          x.exchangeCode == values.exchangeCode &&
          x.isEdit != true
        ) {
          flag = true;
        }

        return flag == true;
      });
      if (t) {
        const msg = '同一个持仓类型下证券代码、交易市场、持仓日期、交易属性不可以重复';
        message.warning(msg);
        return;
      }
      if (values.secType == 'HG' && !values.repoType) {
        message.warning('回购类型必须填写');
        return;
      }
      this.setState(
        {
          dataSource: dataSource.map((x) => {
            if (x.id == editRow?.id) {
              delete x.isEdit;
              if (x.editType === 'add') {
                x.bottomUninvestPosition = 0; // 新增的行，后端需要一个标志位 固定值0
              }
              return { ...x, id: editRow.id, ...values, positionDate: values.positionDate?.format('YYYY-MM-DD') };
            } else {
              return x;
            }
          }), // 原后端多给的数据 也要保存 方便传递给后端
          editRow: undefined,
          positionType: undefined,
        },
        () => {
          this.props.onChange(this.state.dataSource);
        },
      );
    });
  };

  // 取消
  cancelItem = (e) => {
    const { dataSource, editRow } = this.state;
    const { form } = this.props;

    this.setState({
      dataSource:
        editRow?.editType == 'add'
          ? dataSource.filter((x) => x.id != editRow.id)
          : dataSource.map((x) => {
              if (x.id == editRow.id) {
                const { isEdit, ...other } = x;
                return other;
              }
              return x;
            }),
      editRow: undefined,
      positionType: undefined,
    });
    form.resetFields();
  };

  // 编辑
  editItem = (row) => {
    const {
      globalM: {
        dataDictionary: { POSITION_TYPE = [], ENTRUSTED_INVESTMENT_HOLD_SEC_TYPE = [] },
      },
    } = this.props;
    const { dataSource, editRow } = this.state;
    const { form } = this.props;
    const { setFieldsValue } = form;
    if (editRow) {
      message.warning('有正在编辑中的证券，请保存后再进行操作');
      return;
    }
    this.setState(
      {
        editRow: row,
        positionType: row.positionType,
        disabledRepoType: row.secType != 'HG',
        dataSource: dataSource.map((x) => {
          if (row.id == x.id) {
            return {
              ...row,
              isEdit: true,
            };
          } else {
            return x;
          }
        }),
      },
      () => {
        setFieldsValue({ ...row, positionDate: moment(row.positionDate) });
      },
    );
  };

  // 删除
  deleteItem = (row) => {
    const { dataSource, editRow } = this.state;
    if (editRow) {
      message.warning('有正在编辑中的证券，请保存后再进行操作');
      return;
    }
    this.setState(
      {
        dataSource: dataSource.filter((x) => x.id != row.id),
      },
      () => {
        this.props.onChange(this.state.dataSource);
      },
    );
  };

  render() {
    const { columns, dataSource, editRow = {}, dictArr = [], positionType } = this.state;
    const {
      globalM: {
        dataDictionary: { POSITION_TYPE = [], cashSecType = [], ENTRUSTED_INVESTMENT_HOLD_SEC_TYPE = [], ENTRUSTED_INVESTMENT_HOLD_ATTRCODE = [] },
      },
    } = this.props;
    if (columns?.length && columns[columns?.length - 1].title != '操作' && this.props.type == 1) {
      columns.push({
        title: '操作',
        width: 100,
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        operates: [],
      });
    }

    const newColumns = columns?.map((x) => {
      // 证券代码
      if (x.key == 'assetDebtCode') {
        return {
          ...x,
          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <InputC
                  disabled={positionType == 'XJZC'}
                  form={this.props.form} // form对象
                  dataIndex={'assetDebtCode'}
                  rules={[{ required: true, message: '请输入证券代码' }]}
                  max={40}
                />
              );
            } else {
              return text ?? '--';
            }
          },
        };
      }
      // 证券名称
      if (x.key == 'secuabbr') {
        return {
          ...x,
          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <InputC
                  form={this.props.form} // form对象
                  dataIndex={'secuabbr'}
                  rules={[{ required: true, message: '请输入证券名称' }]}
                  onChange={(e) => {
                    // 现金资产 名称和代码是一样的
                    if (positionType == 'XJZC')
                      this.props.form.setFieldsValue({
                        assetDebtCode: e?.target?.value || '',
                      });
                  }}
                />
              );
            } else {
              return text || '--';
            }
          },
        };
      }
      // 持仓类型
      if (x.key == 'positionType') {
        return {
          ...x,
          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <SelectC
                  positionBody={true}
                  onChange={(e) => {
                    this.props.form.setFieldsValue({
                      secType: undefined,
                      repoType: undefined,
                    });
                    this.setState({
                      positionType: e,
                      disabledRepoType: true,
                    });
                    // 现金资产时修改一些默认值
                    if (e == 'XJZC') {
                      this.props.form.setFieldsValue({
                        assetDebtCode: '',
                        attrCode: undefined,
                        exchangeCode: '999',
                        bottomPositionNum: 0,
                        unitCost: 0,
                      });
                    }
                  }}
                  form={this.props.form} // form对象
                  dataIndex={'positionType'}
                  rules={[{ required: true, message: '请输入持仓类型' }]}
                  dataSource={formSelectData(POSITION_TYPE.filter((item) => item.code !== 'FEE'))}
                />
              );
            } else {
              return findValueByCode(text, POSITION_TYPE) || '--';
            }
          },
        };
      }
      // 资产类型
      if (x.key == 'secType') {
        return {
          ...x,
          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <SelectC
                  disabled={!this.state.positionType}
                  positionBody={true}
                  form={this.props.form} // form对象
                  dataIndex={'secType'}
                  rules={[{ required: true, message: '请输入资产类型' }]}
                  dataSource={
                    positionType == 'XJZC' ? formSelectData(cashSecType) : formSelectData(ENTRUSTED_INVESTMENT_HOLD_SEC_TYPE).filter((item) => !dictArr.includes(item.code))
                  }
                  onChange={(e) => {
                    this.props.form.setFieldsValue({
                      repoType: undefined,
                    });
                    // 回购类型是否可选
                    if (e != 'HG') {
                      this.setState({
                        disabledRepoType: true,
                      });
                    } else {
                      this.setState({
                        disabledRepoType: false,
                      });
                    }
                  }}
                />
              );
            } else {
              return findValueByCode(text, ENTRUSTED_INVESTMENT_HOLD_SEC_TYPE.concat(cashSecType));
            }
          },
        };
      }
      // 回购类型
      if (x.key == 'repoType') {
        return {
          ...x,
          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <SelectC
                  positionBody={true}
                  form={this.props.form} // form对象
                  dataIndex={'repoType'}
                  dataSource={[
                    { value: '质押式', title: '质押式' },
                    { value: '协议式', title: '协议式' },
                  ]}
                  disabled={this.state.disabledRepoType}
                />
              );
            } else {
              return record.secType == 'HG' ? text || '--' : '';
            }
          },
        };
      }
      // 交易属性
      if (x.key == 'attrCode') {
        return {
          ...x,
          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <SelectC
                  disabled={positionType == 'XJZC'}
                  positionBody={true}
                  form={this.props.form} // form对象
                  dataIndex={'attrCode'}
                  rules={[{ required: positionType != 'XJZC', message: '请选择交易类型' }]}
                  dataSource={formSelectData(ENTRUSTED_INVESTMENT_HOLD_ATTRCODE)}
                  // max={40}
                />
              );
            } else {
              return findValueByCode(text, ENTRUSTED_INVESTMENT_HOLD_ATTRCODE) || '--';
            }
          },
        };
      }
      // 交易市场
      if (x.key == 'exchangeCode') {
        return {
          ...x,
          width: 150,
          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <TradingMarketC
                  positionBody={true}
                  disabled={positionType == 'XJZC'}
                  form={this.props.form} // form对象
                  title=''
                  dataIndex={'exchangeCode'}
                  marketType={['jys', 'yhj', 'cw', 'qiquan', 'qt']}
                  fromPage={'guzhi'}
                  width={130}
                  rules={[{ required: true, message: '请选择交易市场' }]}
                />
              );
            } else {
              return (
                config.filter((item) => {
                  return item.value == text;
                })[0]?.title || '--'
              );
            }
          },
        };
      }
      // 持仓数量
      if (x.key == 'bottomPositionNum') {
        return {
          ...x,
          type: 'money',
          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <InputNumberC
                  form={this.props.form} // form对象
                  dataIndex={'bottomPositionNum'}
                  disabled={positionType == 'XJZC'}
                  precision={2}
                  max={999999999999}
                  splitStyle={true}
                  rules={[{ required: true, message: '请输入持仓数量' }]}
                />
              );
            } else {
              return `${text !== null || text !== undefined ? accounting.formatNumber(Number(text), 2) : '--'}`;
            }
          },
        };
      }
      // 单位成本
      if (x.key == 'unitCost') {
        return {
          ...x,
          type: 'money',
          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <InputNumberC
                  form={this.props.form} // form对象
                  dataIndex={'unitCost'}
                  disabled={positionType == 'XJZC'}
                  precision={2}
                  max={999999999999}
                  splitStyle={true}
                  rules={[{ required: true, message: '请输入单位成本' }]}
                />
              );
            } else {
              return `${text !== null || text !== undefined ? accounting.formatNumber(Number(text), 2) : '--'}`;
            }
          },
        };
      }
      // 总成本
      if (x.key == 'costPrice') {
        return {
          ...x,
          type: 'money',
          render: (text, record) => {
            if (record.id == editRow.id) {
              // eslint-disable-next-line max-lines
              return (
                // eslint-disable-next-line max-lines
                <InputNumberC
                  form={this.props.form} // form对象
                  dataIndex={'costPrice'}
                  precision={2}
                  max={999999999999}
                  min={-9999999999999}
                  splitStyle={true}
                  rules={[{ required: true, message: '请输入总成本' }]}
                />
              );
            } else {
              return `${text !== null || text !== undefined ? accounting.formatNumber(Number(text), 2) : '--'}`;
            }
          },
        };
      }

      // 折算人民币市值
      if (x.key == 'bottomAssetRMBValue') {
        return {
          ...x,
          type: 'money',
          width: 150,
          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <InputNumberC
                  form={this.props.form} // form对象
                  dataIndex={'bottomAssetRMBValue'}
                  precision={2}
                  max={999999999999}
                  min={-9999999999999}
                  // unit={'元'}
                  splitStyle={true}
                  rules={[{ required: true, message: '请输入折算人民币市值' }]}
                />
              );
            } else {
              return `${text !== null || text !== undefined ? accounting.formatNumber(Number(text), 2) : '--'}`;
            }
          },
        };
      }
      // 持仓日期
      if (x.key == 'positionDate') {
        return {
          ...x,
          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <SingleDateC
                  form={this.props.form} // form对象
                  dataIndex={'positionDate'}
                  disabled={true}
                  initialValue={moment(this.props.date)}
                />
              );
            } else {
              return text || '--';
            }
          },
        };
      }
      if (x.key == 'operate') {
        return {
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          width: 100,
          type: 'operate',
          operates: [
            {
              title: '保存',
              onClick: (record) => {
                this.saveItem(record);
              },
              rules: {
                // 点击保存或取消时隐藏保存和取消按钮，展示编辑和删除按钮
                hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['='] }] },
              },
            },
            {
              title: '取消',
              onClick: (record, index) => {
                this.cancelItem(record);
              },
              rules: {
                // 点击保存或取消时隐藏保存和取消按钮，展示编辑和删除按钮
                hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['='] }] },
              },
            },
            {
              title: '编辑',
              onClick: (record, index) => {
                this.editItem(record);
              },
              rules: {
                hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['!='] }] },
              },
            },
            {
              title: '删除',
              onClick: (record) => {
                this.deleteItem(record);
              },
              rules: {
                hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['!='] }] },
              },
            },
          ],
        };
      }
      return x;
    });
    const tempNum = document?.documentElement?.offsetHeight ? document.documentElement.offsetHeight - 180 - 312 : undefined;
    const tableHeight = tempNum ? (tempNum < 250 ? 250 : tempNum) : 250; // 最小高度设置250
    return (
      <>
        {this.props.date && this.props.type == '1' && <PrimaryC title='新增' style={{ marginTop: '10px' }} onClick={() => this.add()} />}
        <div style={{ marginTop: '20px' }}>
          <TableC
            columns={newColumns}
            dataSource={dataSource}
            rowKey='id'
            hidePage={true}
            scroll={{ x: '100%', y: `${tableHeight}px` }}
            // components={VTComponents({
            // 	id: valuateAnalysisTable,
            // 	destroy: false
            // })}
          />
        </div>
      </>
    );
  }
}
